/*  
 * i-OSGi - Tunable Bundle Isolation for OSGi
 * Copyright (C) 2011  Sven Schulz
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.iosgi.ie.os;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.ConnectException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;

import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Provides;
import org.apache.felix.ipojo.annotations.Requires;
import org.apache.felix.ipojo.annotations.ServiceProperty;
import org.iosgi.Constants;
import org.iosgi.IsolationEnvironmentFactory;
import org.iosgi.impl.Debug;
import org.iosgi.impl.EnvironmentIDs;
import org.iosgi.impl.Utils;
import org.iosgi.outpost.Client;
import org.iosgi.outpost.OperationExecutionException;
import org.iosgi.outpost.util.ipr.MacAddress;
import org.iosgi.outpost.util.ipr.Registry;
import org.iosgi.util.Network;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.virtualbox_4_0.AccessMode;
import org.virtualbox_4_0.CleanupMode;
import org.virtualbox_4_0.DeviceType;
import org.virtualbox_4_0.IAppliance;
import org.virtualbox_4_0.IConsole;
import org.virtualbox_4_0.IKeyboard;
import org.virtualbox_4_0.IMachine;
import org.virtualbox_4_0.IMedium;
import org.virtualbox_4_0.INetworkAdapter;
import org.virtualbox_4_0.IProgress;
import org.virtualbox_4_0.ISession;
import org.virtualbox_4_0.IVirtualBox;
import org.virtualbox_4_0.LockType;
import org.virtualbox_4_0.MachineState;
import org.virtualbox_4_0.VirtualBoxManager;

/**
 * @author Sven Schulz
 */
@Component(immediate = true)
@Provides(specifications = { IsolationEnvironmentFactory.class })
public class OperatingSystemIEFactory implements IsolationEnvironmentFactory {

	private static final Random RANDOM = new Random();
	private static final Logger LOGGER = LoggerFactory
			.getLogger(OperatingSystemIEFactory.class);
	private static final AtomicInteger nextId = new AtomicInteger(1);

	static String getRandomMACAddress() {
		int[] mac = { 0x00, 0x07, 0xE9, 0, 0, 0 };
		for (int i = 3; i < 6; i++) {
			mac[i] = RANDOM.nextInt(256);
		}
		StringBuilder b = new StringBuilder();
		for (int i : mac) {
			String s = Integer.toHexString(i);
			b.append(s.length() == 2 ? s : "0" + s);
		}
		return b.toString();
	}

	private File base = new File(
			"C:\\Users\\schulzs\\Documents\\Workspaces\\i-OSGi\\iosgi\\build\\resources\\appliances");
	private File appliance = new File(base, "microcore.ova");
	private File image = new File(base, "microcore-current.iso");

	@Requires
	private Network network;

	@Requires
	private VirtualBox virtualBox;

	private final URI id;

	@SuppressWarnings("unused")
	@ServiceProperty(name = Constants.R_OSGI_REGISTRATION)
	private boolean publishRemotely = Boolean.TRUE;

	private Registry registry;
	private BundleContext context;

	public OperatingSystemIEFactory(BundleContext context) {
		this.context = context;
		registry = Registry.getRegistry();
		id = URI.create("/");
	}

	@Override
	public URI getId() {
		return id;
	}

	VirtualBoxManager connect() {
		LOGGER.debug("connecting to virtual box remote service");
		VirtualBoxManager vboxMgr = VirtualBoxManager.createInstance(null);
		URL url = virtualBox.getManagerUrl();
		vboxMgr.connect(url.toString(), "user", "pwd");
		LOGGER.debug(
				"connection to virtual box remote service established (Version: {})",
				vboxMgr.getVBox().getVersion());
		return vboxMgr;
	}

	void disconnect(VirtualBoxManager vboxMgr) {
		vboxMgr.disconnect();
		vboxMgr.cleanup();
	}

	@Override
	public synchronized URI newIsolationEnvironment(
			Map<String, Object> properties) throws IOException,
			TimeoutException, InterruptedException {
		cleanup();
		URI nid = URI.create("/" + nextId.getAndIncrement() + "/0");
		VirtualBoxManager vboxMgr = null;
		try {
			vboxMgr = this.connect();
			IVirtualBox vbox = vboxMgr.getVBox();
			ISession s = vboxMgr.getSessionObject();
			IMachine machine = this.importAppliance(vbox, s);
			/* TODO Headless */
			IProgress p = machine.launchVMProcess(s, "gui", "");
			p.waitForCompletion(-1);
			Thread.sleep(3000);
			IConsole c = s.getConsole();
			String opt = "microcore home=hda1\n";
			send(opt, c.getKeyboard());
			Client oc = this.getOutpost(s, vbox);
			File deployDir = new File("i-osgi");
			deploy(oc, deployDir);
			launch(oc, deployDir, nid);
			oc.close();
		} catch (Exception e) {
			throw new IOException("failed to create VM", e);
		} finally {
			disconnect(vboxMgr);
		}
		Utils.waitForIsolatedFramework(context, nid, 1, TimeUnit.MINUTES);
		return EnvironmentIDs.getParent(nid);
	}

	private synchronized void cleanup() {
		VirtualBoxManager vboxMgr = this.connect();
		try {
			IVirtualBox vbox = vboxMgr.getVBox();
			for (IMachine m : vbox.getMachines()) {
				if (m.getState() != MachineState.PoweredOff
						|| !m.getName().startsWith("iosgi-")) {
					continue;
				}
				LOGGER.debug("cleaning up {}", m.getName());
				long ref = System.currentTimeMillis();
				try {
					List<IMedium> media = m
							.unregister(CleanupMode.DetachAllReturnHardDisksOnly);
					IProgress p = m.delete(media);
					p.waitForCompletion(-1);
				} catch (Exception e) {
					LOGGER.error("cleaning up " + m.getName() + " failed", e);
				}
				long elapsed = System.currentTimeMillis() - ref;
				LOGGER.debug("cleaned up {} in {} ms",
						new Object[] { m.getName(), elapsed });
			}
		} finally {
			disconnect(vboxMgr);
		}
	}

	private void launch(Client oc, File deployDir, URI nid)
			throws InterruptedException, OperationExecutionException,
			SocketException {
		List<String> command = new ArrayList<String>();
		command.add("../jre/bin/java");
		command.add("-Dorg.osgi.framework.bootdelegation=com.sun.xml.internal.ws.api.message");
		if (Debug.isDebugEnabled()) {
			command.add("-Xdebug");
			command.add("-Xrunjdwp:transport=dt_socket,server=y,suspend="
					+ (Debug.isSuspendEnabled() ? "y" : "n") + ",address="
					+ Long.toString(10000));
		}
		command.add("-D" + Constants.ENVIRONMENT_ID + "=" + nid);
		command.add("-jar");
		command.add("org.apache.felix.main-3.0.6.jar");
		oc.execute(command, deployDir, false, new File(deployDir, "out"),
				new File(deployDir, "err"));
	}

	private void deploy(Client oc, File deployDir) throws IOException,
			InterruptedException, OperationExecutionException,
			FileNotFoundException {
		final String[] exclude = new String[] { "appliances/", "felix-cache/",
				"work/", "iosgi\\.log" };
		oc.put(new File("."), deployDir, new FileFilter() {
			@Override
			public boolean accept(File pathname) {
				String pn = pathname.getAbsolutePath()
						.replaceAll(
								(File.separator.equals("\\") ? "\\\\"
										: File.separator), "/");
				if (pathname.isDirectory() && !pn.endsWith("/"))
					pn += "/";
				for (String e : exclude) {
					if (Pattern.compile(e).matcher(pn).find()) {
						LOGGER.debug("skipping {} (matched {})", pathname, e);
						return false;
					}
				}
				return true;
			}
		});
		Properties config = new Properties();
		config.load(new FileReader("conf" + File.separator
				+ "config.properties"));
		config.setProperty("org.iosgi.util.configuration.dir",
				"./conf/process/os/");
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		config.store(baos, "This file has been generated by i-OSGi");
		oc.put(baos.toByteArray(), new File(deployDir, "conf" + File.separator
				+ "config.properties"));

		/* Configure service bus. */
		File f = new File("conf" + File.separator + "process" + File.separator
				+ "org.iosgi.servicebus.ServiceBus-0.cfg");
		config.clear();
		config.load(new FileReader(f));
		config.setProperty("serverAddress", network.getAddress()
				.getHostAddress());
		baos = new ByteArrayOutputStream();
		config.store(baos, "This file has been generated by i-OSGi");
		oc.put(baos.toByteArray(), new File(deployDir, f.getPath()));
	}

	private IMachine importAppliance(IVirtualBox vbox, ISession s) {
		IAppliance app = vbox.createAppliance();
		IProgress p = app.read(appliance.getAbsolutePath());
		p.waitForCompletion(-1);
		app.interpret();
		Set<String> oids = this.getMachineIds(vbox);
		p = app.importMachines();
		p.waitForCompletion(-1);
		IMachine machine = null;
		for (IMachine m : vbox.getMachines()) {
			if (!oids.contains(m.getId())) {
				machine = m;
				break;
			}
		}
		machine.lockMachine(s, LockType.Write);
		IMachine mm = s.getMachine();
		mm.setName("iosgi-" + Long.toHexString(System.currentTimeMillis()));
		mm.getNetworkAdapter(0L).setMACAddress(getRandomMACAddress());
		IMedium medium = vbox.openMedium(image.getAbsolutePath(),
				DeviceType.DVD, AccessMode.ReadOnly);
		mm.mountMedium("IDE-Controller", 1, 0, medium, true);
		mm.saveSettings();
		s.unlockMachine();
		return machine;
	}

	Client getOutpost(ISession session, IVirtualBox vbox) throws Exception {
		Set<InetAddress> addresses = this.getVMInetAddresses(session, vbox);
		while (true) {
			for (InetAddress addr : addresses) {
				Client oc = new Client(addr.getHostAddress(), this.getClass()
						.getClassLoader());
				try {
					oc.connect(1, TimeUnit.SECONDS);
				} catch (ConnectException ce) {
					LOGGER.debug("connection attempt failed", ce);
				}
				return oc;
			}
		}
	}

	Set<InetAddress> getVMInetAddresses(ISession session, IVirtualBox vbox)
			throws Exception {
		Set<InetAddress> addresses = new HashSet<InetAddress>();
		IMachine m = session.getMachine();
		long count = 1;// vbox.getSystemProperties().getNetworkAdapterCount();
		for (long i = 0; i < count; i++) {
			INetworkAdapter a = m.getNetworkAdapter(i);
			String raw = a.getMACAddress();
			InetAddress addr = registry.get(new MacAddress(raw), 30,
					TimeUnit.SECONDS);
			addresses.add(addr);
		}
		return addresses;
	}

	void send(String command, IKeyboard keyboard) {
		for (int i = 0; i < command.length(); i++) {
			int[] codes = Scancodes.getScancodes(command.charAt(i));
			for (int c : codes) {
				keyboard.putScancode(c);
			}
		}
	}

	String getHostAddress() throws SocketException {
		for (Enumeration<NetworkInterface> e = NetworkInterface
				.getNetworkInterfaces(); e.hasMoreElements();) {
			NetworkInterface intf = e.nextElement();
			if (intf.isLoopback() || !intf.isUp() || intf.isVirtual()) {
				continue;
			}
			for (InterfaceAddress addr : intf.getInterfaceAddresses()) {
				InetAddress inetAddr = addr.getAddress();
				if (addr.getAddress() instanceof Inet4Address) {
					return inetAddr.getHostAddress();
				}
			}
		}
		return null;
	}

	Set<String> getMachineIds(IVirtualBox vbox) {
		Set<String> ids = new HashSet<String>();
		for (IMachine m : vbox.getMachines()) {
			ids.add(m.getId());
		}
		return ids;
	}

}